
require "common/Define"
require "Exm/BallMediator"
-- require "System/Timer"

local TickManager = CS.PengLuaKit.TickManager;
local fCountTime = .0;
local fMaxCountTime = 1.0 * 20;
local PLKEventDispatcher = CS.PengLuaKit.PLKEventDispatcher;

-- lua start interface
function Main()
	print("--- Game Main called! ---");
	math.randomseed(tostring(os.time()):reverse():sub(1, 6))   
	BallMediator:Awake();

	-- wait 10 seconeds 
	-- Timer.New(OnTimeoutHandler, 10, 1, false):Start();

	local tickManager = TickManager.Instance();
	tickManager:AddFrameTickListener(OnUpdateTickHandler, false);

	-- event from unity handler
	PLKEventDispatcher.AddLuaEventListener("SendFromUnityEvent", OnUnityEventHandler);
end

function OnUpdateTickHandler(delta)
	-- body
	fCountTime = fCountTime + delta;
	-- print("fCountTime=" .. fCountTime .. ", fMaxCountTime=" .. fMaxCountTime);
	if fCountTime > fMaxCountTime then
		OnTimeoutHandler();
	end
end

function OnTimeoutHandler()
	-- body
	BallMediator:Dispose();

	-- stop
	local tickManager = TickManager.Instance();
	tickManager:RemoveFrameTickListener(OnUpdateTickHandler);

	-- send notify to unity
	print("Dispatch lua event...");
	PLKEventDispatcher.DispatcherEvent("SendFromLuaEvent", "to unity");
end

function OnUnityEventHandler( ... )
	-- body
	local eventData = select(1, ...);
	print("Lua listened event, event=SendFromUnityEvent, eventData", eventData);
end